'use strict'

const _ = require('underscore')
const AV = require('leanengine')

module.exports = function (options) {
  return new Match(options)
}

class Match {

  constructor (options) {

    _.extend(this, {
      teams: options.teams,
      umpire: options.umpire,
      discipline: options.discipline,
      scoringSys: options.scoringSys,
      bestOf: options.bestOf,
      duration: options.duration,
      winner: options.winner,
      games: options.games
    })

    this.maxConsecutivePoints = null
    this.scoringArr = null

  }

  init (p) {

    this.scoringSys = _.isNumber(p.scoringSys) ? p.scoringSys : new Error('scoringSys must be a string')
    this.numberOfGames = _.isNumber(p.numberOfGames) ? p.numberOfGames : new Error('numberOfGames must be a string')
    this.discipline = isDiscipline(p.discipline) ? p.discipline : new Error(`discipline must be one of 'ms', 'md', 'ws', 'wd', 'xd'`)
    this.teams = isTeams(p.teams) ? p.teams : new Error()
    this.umpire = isUmpire(p.umpire) ? p.umpire : new Error()

    return this
  }

  getMaxConsecutivePoints () {
    var scoringArr = this.scoringArr || this.getScoringArr()
    return scoringArr.map(g => {
      return g.map(el => {
        var consecutiveArr = []
        var c = 0
        var len = el.length
        el.forEach((p, i) => {
          if (p > el[i - 1] && i === len - 1) { // 连续的
            c++
            consecutiveArr.push(c)
            c = 0
          } else if (p > el[i - 1]) {
            c++
          } else {
            consecutiveArr.push(c)
            c = 0
          }
        })
        return _.max(consecutiveArr)
      })
    })
  }

  // getMatchMaxConsecutivePoints () {
  //   var consecutivePoints = getMaxConsecutivePoints()
  //   var max
  //   consecutivePoints.map(el => {
  //     return el.reduce((x, y) => {
  //       if (x > y) return {
  //
  //       }
  //     })
  //   })
  // }

  getScoringArr () {

    this.scoringArr = this.games.map(g => {
      return [0, 1].map(i => {
        var r = g.scoresFlow.map((el, index) => {
          if (el.scoredTeam === i) return el.currentScore
          if (index === 0) return 0
          return null
        })
        for (let i = 0, len = r.length; i < len; i++) {
          if (r[i] === null) r[i] = r[i - 1]
        }
        r.unshift(0)
        return r
      })
    })

    return this.scoringArr

  }

  save () {

  }



}

function inArray (str, arr) {
  if (arr.indexOf(str) !== -1) return true
  return false
}

function isDiscipline (str) {
  return inArray(str, ['ms', 'md', 'ws', 'wd', 'xd'])
}
